#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
require Exporter;
use strict;
use SIM_settings;
use SIM_base;
use SIM_cgi;
use CGI qw(param);
use CiscoTalkOO;

#my $httpUser = $ENV{'REMOTE_USER'} || die "Oops no env found for SREMOTE_USER.";
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];
my $option4 = $ARGV[6];

sub printHead {
  my $dispHead = "@_[0]";
  my $linkColor = "black";
  print("
        <TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR BGCOLOR=#EEEEEE><TD COLSPAN=3><CENTER>
        Devicetypes: ");
  my @devTypes = split(' ', $SIMparam{'SIMremExecDevTypes'});
  foreach my $entry (@devTypes) {
    my $workDir = "$SIMparam{'SIMdeviceDir'}/$entry";
    if ( ! -d $workDir ) {
      print(" <FONT COLOR=LightGrey >$entry</FONT> ");
    } else {
      printEntry("$entry", "List directory $entry.", "$module", "$tool+selectDevices+$entry", "2", "$module", "$tool+$action+$option1", "", "line", "", $linkColor);
    }
  }
  print("
	</TD></TR>
	</TABLE>
	<CENTER>
        ");
}

sub printSelect {
  my $vendorType = "@_[0]";
  my $selection = "@_[1]";

  print("Select:
          <A HREF=$httpScriptName?$module+$tool+selectDevices+$vendorType+none>none</A> ");
  open( FH, $SIMparam{'SIMremExecIosTypes'} ) || die "cannot open SIMremExecIosTypes file.";
  my @lines = <FH>;
  foreach my $regel (@lines) {
    my ( $test, $type, $description ) = split(' ', $regel, 3);
    if (( "$test" eq "type" ) and ( "$type" ne "none" )) {
      print(" <A HREF=$httpScriptName?$module+$tool+selectDevices+$vendorType+$type>$type</A> ");
    }
  }
  print("<A HREF=$httpScriptName?$module+$tool+selectDevices+$vendorType+all>all</A>");
}


sub selectDevices {
  my $vendorType = "@_[0]";
  my $selection = "@_[1]";
  my $workDir = "$SIMparam{'SIMdeviceDir'}/$vendorType";
  if ( ! -d "$workDir" ) {
    print("<H3>Oops, no info found for devicetype $vendorType.</H3>");
  } else {
    my @checks = param('check');
    my $action = param('action');
    my $username = param('username');
    my $password = param('password');
    my $enablePassword = param('enablePassword');
    if (( "$enablePassword" eq "" ) and ( "$password" ne "" )) {
      $enablePassword = $password;
    }
    my $confFile = param('confFile');
    my $commands = param('commands');;
    my $actionStatus = "no";
    my %devicesChecked = ();
    if ( "$action" eq "copyConfig" ) {
      $actionStatus = "yes";
    } elsif (( "$action" eq "confNet" ) and ( -f "$SIMparam{'SIMtftpBaseDir'}/$confFile" )) {
      $actionStatus = "yes";
    } elsif (( "$action" eq "runCmd" ) and ( "$commands" ne "" )) {
      $actionStatus = "yes";
    }
    foreach my $entry (@checks) {
      $devicesChecked{$entry} = "yes";
    }
    chdir $workDir;
    my $phase = 0;
    my $formAction;
    if ( "$checks[0]" eq "" ) {
      print("<H3>Step 1, select your devices</H3><HR>");
      $phase = 1;
      $formAction = "Confirm devices";
    } elsif ( "$actionStatus" eq "no" ) {
      print("<H3>Step 2, configure your action.</H3><HR>");
      $phase = 2;
      $formAction = "Confirm action";
    } elsif (( "$username" eq "" ) or ( "$password" eq "" )) {
      print("<H3>Step 3, confirm your action with your device userid and password.</H3><HR>");
      $phase = 3;
      $formAction = "Execute script";
    } elsif (( "$username" ne "" ) and ( "$password" ne "" ) and ( "$enablePassword" ne "" )) {
      print("<H3>Step 4, Executing the login script.</H3><HR>");
      $phase = "exec";
    }
    if ( "$phase" ne "exec" ) {
      printSelect( $vendorType, $selection );
      print("
        <FORM method=post Action=$httpScriptName?$module+$tool+selectDevices+$vendorType>
        <TABLE><TR BGCOLOR=#FF8800><TD></TD><TD>Device name</TD><TD>Device type</TD><TD>Syntax</TD></TR>");
      my @deviceList = ();
      if ( "$phase" eq "1" ) {
        @deviceList = <*>;
      } else {
        @deviceList = @checks;
      }
      my %oidIosType = ();
      foreach my $entry (@deviceList) {
        my $ipAddr = catFileLine("$workDir/$entry/ipaddr");
        my $ipDir = getIpDir( $ipAddr );
        my $sipmanrectype = catFileLine("$ipDir/sipmanrectype.txt");
        my $oidInfo = catFileLine("$ipDir/snmpoid.txt");
        my ( $oidName, $oidNum ) = split(' ', $oidInfo);
        if ( "$oidIosType{$oidNum}" eq "" ) {
          my $iodIosEntry = catFileLine("$SIMparam{'SIMoidDir'}/.$oidNum/remExecSyntax");
          if ( "$iodIosEntry" ne "" ) {
            $oidIosType{$oidNum} = $iodIosEntry;
	  }
        }
        my $checked;
#       print("selection=$selection ");
        if ( "$selection" eq "none" ) {
          $checked = "";
        } elsif ( "$oidIosType{$oidNum}" eq "" ) {
          # donet check for devices without sysntax info.
          $checked = "";
        } elsif ( "$sipmanrectype" eq "ext" ) {
          # do not try to login to external devices.
          $checked = "";
        } elsif ( "$selection" eq "all" ) {
          $checked = "CHECKED"; 
        } elsif ( "$selection" eq "$oidIosType{$oidNum}" ) {
          $checked = "CHECKED"; 
        } elsif ( "$devicesChecked{$entry}" eq "yes" ) { 
          $checked = "CHECKED"; 
        }
        print("<TR><TD><INPUT TYPE=\"checkbox\" $checked NAME=check VALUE=$entry></TD>
                   <TD><A HREF=$httpScriptName?mon+nodestatus+$ipAddr>$entry</A></TD>
                   <TD>$oidName</TD>
	  	   <TD>$oidIosType{$oidNum}</TD>
	       </TR>");
      }
      print("</TABLE><TABLE>");
      if ( $phase > 1 ) {
        print("
          <TR><TD>action:</TD><TD><SELECT NAME=\"action\" SIZE=1>
            <OPTION VALUE=$action>$action</OPTION>
            <OPTION VALUE=runCmd>runCmd = run commands on the selected devices.</OPTION>
            <OPTION VALUE=confNet>confNet = configure the network based on a tftp file.</OPTION>
            <OPTION VALUE=copyConfig>copyConfig = copy the running config to the tftp server.</OPTION>
          </SELECT></TD></TR>
              ");
         if ( "$action" eq "runCmd" ) {
	   my $textCmds = $commands;
	   # $textCmds =~ s/\r\n/<BR>/g;
           print("<TR><TD>commands:</TD><TD><TEXTAREA NAME=commands ROWS=10 COLS=80>$commands</TEXTAREA>");
         } elsif ( "$action" eq "confNet" ) {
           chdir( $SIMparam{'SIMtftpBaseDir'});
           my $workDir = "$SIMparam{'SIMtftpConfigDir'}";
           # print("<TR><TD COLSPAN=2>SIMtftpConfigDir = $workDir</TD></TR>");
	   if ( ! -d "$workDir" ) {
	     print("<TR><TD COLSPAN=2>Oops, template directory SIMtftpConfigDir ($workDir) for confnet not found.</TD></TR>");
           } else { 
	     if ( "$confFile" eq "" ) { $confFile = "none"; }
	     print("<TR><TD>confFile:</TD><TD><SELECT NAME=\"confFile\" SIZE=1>
	              <OPTION VALUE=$confFile>$confFile</OPTION>");
	     my @fileList = <$workDir/*>;
	     foreach my $entry (@fileList) {
	       print("<OPTION VALUE=\"$entry\">$entry</OPTION>");
	     }
	     print("</SELECT></TD></TR>");
	   }
         }
      }
      if ( $phase > 2 ) {
        print("
        <TR><TD>username:</TD><TD><INPUT NAME=username VALUE=\"$username\" SIZE=30></TD></TR>
        <TR><TD>login password:</TD><TD><INPUT NAME=password VALUE=\"$password\" SIZE=30 TYPE=password></TD></TR>
        <TR><TD>enable password:</TD><TD><INPUT NAME=enablePassword VALUE=\"$enablePassword\" SIZE=30 TYPE=password></TD></TR>
              ");
      }
      print("</TABLE>");
      print("<INPUT TYPE=submit Value=\"$formAction\">
  	     </FORM>");
    } else {
      # execute login script.
      my @termCmds = ();
      if ( "$action" eq "confNet" ) {
        push( @termCmds, "copy tftp://$SIMparam{'SIMtftpServer'}/$confFile  run\n");
	push( @termCmds, "\n");
	push( @termCmds, "\n");
	push( @termCmds, "\n");
	push( @termCmds, "\n");
	push( @termCmds, "\n");
      } elsif ( "$action" eq "runCmd" ) {
        @termCmds = join('\r\n', $commands);
      } elsif ( "$action" eq "copyConfig" ) {
        push( @termCmds, "\n");
      }
      foreach my $entry (@checks) {
        my @runCmds = @termCmds;
        my $device = catFileLine("$workDir/$entry/ipaddr");
        # test syntax type for term length command.
        my $ipDir = getIpDir( $device );
        my $oidInfo = catFileLine("$ipDir/snmpoid.txt");
        my ( $oidName, $oidNum ) = split(' ', $oidInfo);
        my $syntaxType = catFileLine("$SIMparam{'SIMoidDir'}/.$oidNum/remExecSyntax");

        if ( "$syntaxType" eq "ios" ) {
          unshift( @runCmds, "term len 0\n" );
        } elsif ( "$syntaxType" eq "asa" ) {
          unshift( @runCmds, "term pag 0\n" );
        } elsif ( "$syntaxType" eq "cat" ) {
          unshift( @runCmds, "set len 0\n" );
        }
        print("<H3>-------------------- $entry ($device) --------------------</H3></CENTER><PRE>");
	if ( "$device" ne "" ) {
	  my $device = new CiscoTalkOO($device, $username, $password, $enablePassword);
	  $device->StartTalking();
	  if ( $device->{spawn_ok} == 1 ) {
            if ( "$action" eq "copyConfig" ) {
              my $fileIdent = rand(1000000);
              $device->DoCopyConfigToTFTP($SIMparam{'SIMtftpServer'}, "conf-$fileIdent-$$");
            } else {
	      push @runCmds, "\n";
	      $device->DoExecute( \@runCmds);
	      $device->DoExit();
	      $device->GoodBye();
            }
	  }
	  my $info = $device->PrintReport();
	  print("$info");
	}
        print("</PRE><CENTER>");
      }
    }
  }
}

#--------------------------- Main ---------------------------
printHead;


if (( "$action" eq "none" ) or ( "$option1" eq "" )) {
  print("<H3>Please select an devicetype above.</H3>");
} elsif ( "$action" eq "selectDevices" ) {
  selectDevices( $option1, $option2 );
} elsif ( "$action" eq "createAction" ) {
  createAction( $option1 );
} else {
  print("Oops, action $action not found.");
}
